package org.springframework.samples.petclinic.controllers.EnterControls;

import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.samples.petclinic.Services.UserServices;
import org.springframework.samples.petclinic.model.owner.Owner;
import org.springframework.samples.petclinic.model.usrAccount.Account;
import org.springframework.samples.petclinic.system.ClientType;
import org.springframework.samples.petclinic.system.WebSecurityConfig;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@Controller
public class UsrEnterController {
	private final UserServices userServices;
	public UsrEnterController(UserServices userServices) {
		this.userServices = userServices;
	}


	@GetMapping("ownerLogin")
	public String ownerLogin(HttpSession session){
		return "/ownerLogin";
	}

	@PostMapping("/ownerLoginPost")
	public String varify(@RequestParam(value = "ownername")String accountName, @RequestParam(value = "ownerpassword")String password, HttpSession session){
		if (userServices.verifyPasword(accountName,password)){
			session.setAttribute(WebSecurityConfig.SESSION_KEY, accountName);
			session.setAttribute(WebSecurityConfig.TYPE, ClientType.USER_TYPE);
			return "ownerWelcome";
		}
		else return "/ownerLogin";
	}
	@PostMapping("/usrRegister")
	public String register(@RequestBody Owner newOwner,@RequestParam(value = "password")String password){
		String accountName = newOwner.getAccountName();
		if (userServices.isExist(accountName)) return "user/register";
		else {
			userServices.save(newOwner, password);
			return "redirect:/home";
		}
	}

	@GetMapping("usrLogout")
	public String logout(HttpSession session){
		session.removeAttribute(WebSecurityConfig.SESSION_KEY);
		session.removeAttribute(WebSecurityConfig.TYPE);
		return null;
	}
}
